import React from "react";
import searchCss from "../../assets/cjs/search.module.css";
import store from "../../store/cjs";
import { HOT_SEARCH } from "../../api/cjs/hotSearch";
import { SEARCH_ONLYMUSIC } from "../../api/cjs/searchOnlyeMusic";
import { SEARCH_MAN } from "../../api/cjs/searchMan";
import { SEARCH_MUSICALL } from "../../api/cjs/searchMusicAll";
import { SEARCH_GIVE_YOU_CHANGE } from "../../api/cjs/searchGiveYouChange";

class Search extends React.Component {
  constructor() {
    super();
    this.state = {
      hotsearch: [{}],
      musicHistory: [],
      isTure: false,
      val: "",
      searchOnlyeMusic: { songs: [{ artists: [] }] },
      searchMan: { artists: [{}] },
      searchMusicAll: { playlists: [{}] },
      oldVal: [],
      searchGiveYouChange: { allMatch: [{ keyword: "" }] }
    };
  }
  // 搜索框输入内容保存
  async searchContainer(e) {
    let that = this;
    this.setState({
      val: e.target.value
    });
    if (e.target.value != "") {
      await store.dispatch(SEARCH_GIVE_YOU_CHANGE(e.target.value));
      if (store.getState().searchGiveYouChange.allMatch) {
        that.setState({
          searchGiveYouChange: store.getState().searchGiveYouChange
        });
      }
    } else {
      that.setState({
        searchGiveYouChange: { allMatch: [{ keyword: "" }] }
      });
    }
  }
  componentWillMount() {
    // 获取热搜
    store.dispatch(HOT_SEARCH());

    // 当localStore没有的时候创建一个
    if (!localStorage.getItem("oldVal")) {
      localStorage.setItem("oldVal", JSON.stringify(this.state.oldVal));
    } else {
      this.setState({
        oldVal: JSON.parse(localStorage.getItem("oldVal"))
      });
    }

    let that = this;
    // 当store改变，赋值给state
    setTimeout(function() {
      that.setState({
        hotsearch: store.getState().hotsearch
      });
    }, 1000);
  }
  // 点击返回上一个页面
  // 点击清空搜索框
  fanhui() {
    if (!this.state.isTure) {
      this.props.history.go(-1);
    }
    this.setState({
      isTure: false,
      val: "",
      searchGiveYouChange: { allMatch: [{ keyword: "" }] }
    });
  }
  // 点击搜索按钮
  searchmusic() {
    let that = this;
    // 切换页面
    // 将搜索内容保存到历史记录
    this.setState({
      isTure: true,
      oldVal: [this.state.val, ...this.state.oldVal]
    });
    setTimeout(function() {
      localStorage.setItem("oldVal", JSON.stringify(that.state.oldVal));
    }, 20);

    // 获取输入的数据
    // 连接单曲
    store.dispatch(SEARCH_ONLYMUSIC(this.state.val));
    // 连就歌手
    store.dispatch(SEARCH_MAN(this.state.val));
    // 连接歌单
    store.dispatch(SEARCH_MUSICALL(this.state.val));

    // 获取单曲

    setTimeout(function() {
      that.setState({
        searchOnlyeMusic: store.getState().searchOnlyeMusic,
        searchMan: store.getState().searchMan,
        searchMusicAll: store.getState().searchMusicAll
      });
    }, 500);
  }
  // 点击传歌曲
  getsongid(i) {
    let songid1 = this.state.searchOnlyeMusic.songs[i].id;
    let songid = { i: i, id: songid1 };

    localStorage.setItem("songid", JSON.stringify(songid));
  }
  // 点击传歌单
  getmusicAll(i, id, picUrl, playCount, name) {
    let obj = {};
    obj.id = id;
    obj.picUrl = picUrl;
    obj.playCount = playCount;
    obj.name = name;
    localStorage.setItem("songdata", JSON.stringify(obj));
    this.props.history.push("/detail");
  }
  // 点击传歌手
  biubiubiuMusicMan(id) {
    localStorage.setItem("SingerId", id);
    this.props.history.push("/Songer");
  }
  // 点击跳转热搜
  hotSearchClick(item) {
    let that = this;
    setTimeout(function() {
      that.setState({
        val: item,
        isTure: true,
        oldVal: [item, ...that.state.oldVal]
      });

      setTimeout(function() {
        localStorage.setItem("oldVal", JSON.stringify(that.state.oldVal));
      }, 20);

      // 获取输入的数据
      // 连接单曲
      store.dispatch(SEARCH_ONLYMUSIC(that.state.val));
      // 连就歌手
      store.dispatch(SEARCH_MAN(that.state.val));
      // 连接歌单
      store.dispatch(SEARCH_MUSICALL(that.state.val));

      setTimeout(function() {
        that.setState({
          searchOnlyeMusic: store.getState().searchOnlyeMusic,
          searchMan: store.getState().searchMan,
          searchMusicAll: store.getState().searchMusicAll
        });
      }, 500);
    }, 200);
  }
  // 点击历史记录删除
  delOldVal(i) {
    let arr = [...this.state.oldVal];
    arr.splice(i, 1);
    localStorage.setItem("oldVal", JSON.stringify(arr));
    this.setState({
      oldVal: [...arr]
    });
  }
  // 点击历史记录搜索
  searchOldVal(item) {
    this.setState({
      val: item
    });
    this.hotSearchClick(item);
  }
  // 点击搜索关键词
  ClickSearch(item) {
    this.setState({
      val: item
    });
    this.hotSearchClick(item);
  }
  render() {
    let that = this;
    let oldValMusic = (
      <div>
        <h1 className={searchCss.hh1}>历史记录</h1>
        <ul className={searchCss.UL}>
          {this.state.oldVal.map(function(item, index) {
            return (
              <li className={searchCss.ULLI} key={index}>
                <span onClick={that.searchOldVal.bind(that, item)}>
                  <i className={searchCss.I}>♫</i>&nbsp;&nbsp;{item}
                </span>
                <h4
                  className={searchCss.ULLIH4}
                  onClick={that.delOldVal.bind(that, index)}
                >
                  ×
                </h4>
              </li>
            );
          })}
        </ul>
      </div>
    );

    // 热搜
    let hotSearchComponent = (
      <div className={searchCss.hotsearch}>
        <h1 className={searchCss.hh1}>热搜榜</h1>
        <ul className={searchCss.oneUl}>
          {this.state.hotsearch.map(function(item, index) {
            return (
              <li
                key={index}
                className={searchCss.list}
                onClick={that.hotSearchClick.bind(that, item.first)}
              >
                {item.first}
              </li>
            );
          })}
        </ul>

        {/* 历史记录 */}
        {this.state.oldVal.length ? oldValMusic : ""}
      </div>
    );

    // 点击搜索后的歌手
    let SearchMan = () => {
      return (
        <div>
          <h2>相关歌手</h2>
          <ul className={searchCss.musicManUl}>
            {this.state.searchMan.artists.map((item, index) => {
              return (
                <li
                  key={index}
                  className={searchCss.musicManLi}
                  onClick={this.biubiubiuMusicMan.bind(this, item.id)}
                >
                  <span>{item.name}</span>
                  <img
                    src={item.img1v1Url}
                    alt=""
                    className={searchCss.searchManImg}
                  />
                </li>
              );
            })}
          </ul>
        </div>
      );
    };

    // 点击搜索的歌单
    let SearchMusicAll = () => {
      return (
        <div>
          <h2>相关歌单</h2>
          <ul className={searchCss.musicManUl}>
            {this.state.searchMusicAll.playlists.map((item, index) => {
              return (
                <li
                  onClick={this.getmusicAll.bind(
                    this,
                    index,
                    item.id,
                    item.coverImgUrl,
                    item.playCount,
                    item.name
                  )}
                  className={searchCss.musicManLi}
                  key={index}
                >
                  <span className={searchCss.musicSpan}>{item.name}</span>
                  <img
                    src={item.coverImgUrl}
                    className={searchCss.searchManImg}
                  />
                </li>
              );
            })}
          </ul>
        </div>
      );
    };

    // 点击搜索歌曲
    let SearchMusicbiubiubiu = () => {
      return (
        <div>
          <h2>单曲</h2>
          <ul>
            {this.state.searchOnlyeMusic.songs.map((item, index) => {
              return (
                <li
                  onClick={this.getsongid.bind(this, index)}
                  className="hmli"
                  key={index}
                >
                  <div className="index">{index + 1}</div>
                  <div className="indexright">
                    <p className="geming">{item.name}</p>
                    <p className="yanchangzhe">
                      {item.artists.map(function(item, index) {
                        if (index == 0) {
                          return item.name;
                        } else {
                          return "/" + item.name;
                        }
                      })}
                    </p>
                  </div>
                </li>
              );
            })}
          </ul>
        </div>
      );
    };

    // 点击搜索
    let SearchComponent = (
      <div>
        {this.state.searchMan.artistCount ? SearchMan() : ""}
        {this.state.searchMusicAll.playlistCount ? SearchMusicAll() : ""}
        {this.state.searchOnlyeMusic.songCount ? SearchMusicbiubiubiu() : ""}
      </div>
    );
    // 写字出现搜索推荐
    let pullGo = (
      <ul className={searchCss.ULPullGo}>
        {this.state.searchGiveYouChange.allMatch.map(function(item, index) {
          return (
            <li
              onClick={that.ClickSearch.bind(that, item.keyword)}
              className={searchCss.LIPullGo}
              key={index}
            >
              <svg
                t="1571298340716"
                // class="icon"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="2471"
                width="12"
                height="12"
              >
                <path
                  d="M222.6944 222.7968A323.1488 323.1488 0 0 0 133.6832 512c19.2512-87.3728 64.512-172.7488 135.0144-243.3024C339.2512 198.1184 424.6272 152.8832 512 133.632c-101.632-19.1488-210.688 10.5216-289.3056 89.1648z"
                  fill="#969696"
                  p-id="2472"
                ></path>
                <path
                  d="M989.44 822.1184l-121.7024-121.7024a118.016 118.016 0 0 0-92.8-34.1248c114.4576-165.5552 97.92-394.3936-49.4848-541.824-165.9392-165.9904-435.0464-165.9904-601.0368 0-165.9392 165.9904-165.9392 435.1232 0 601.1136 147.4048 147.4304 376.064 163.84 541.7216 49.3824-2.56 33.28 8.8576 67.5328 34.1248 92.8l121.7024 121.728c46.08 45.9776 121.3696 45.9776 167.3472 0 46.208-45.9776 46.208-121.2928 0.128-167.3728zM676.096 676.096c-138.6752 138.6752-363.392 138.6752-502.016 0-138.6752-138.6752-138.6752-363.4432 0-502.1184 138.624-138.6752 363.3408-138.6752 502.016 0 138.6496 138.5728 138.6496 363.4432 0 502.1184z"
                  fill="#969696"
                  p-id="2473"
                ></path>
              </svg>
              &nbsp;&nbsp;{item.keyword}
            </li>
          );
        })}
      </ul>
    );
    return (
      <div>
        <div className={searchCss.nav1}>
          <p onClick={this.fanhui.bind(this)} className={searchCss.p1}></p>
          <input
            type="text"
            className={searchCss.search}
            placeholder="搜索歌名、歌手、歌单"
            value={this.state.val}
            onChange={this.searchContainer.bind(this)}
          />
          <span
            className={searchCss.searchicon}
            onClick={this.searchmusic.bind(this)}
          ></span>
        </div>
        {this.state.isTure === false &&
        this.state.searchGiveYouChange.allMatch[0].keyword !== ""
          ? pullGo
          : ""}
        {this.state.isTure ? SearchComponent : hotSearchComponent}
      </div>
    );
  }
}

export default Search;
